package com.itheima.algorithm.deque;

import com.itheima.algorithm.queue.E01Leetcode102;
import com.itheima.algorithm.queue.LinkedListQueue;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * @author: TylerZhong
 * @description: 二叉树 Z 字层序遍历
 */
public class E01Leetcode103 {
    private static class TreeNode {
        private TreeNode left;
        private int val;
        private TreeNode right;

        public TreeNode(int val) {
            this.val = val;
        }

        public TreeNode(TreeNode left, int val, TreeNode right) {
            this.left = left;
            this.val = val;
            this.right = right;
        }

        @Override
        public String toString() {
            return String.valueOf(val);
        }
    }
    
    public static List<List<Integer>> zigzagLevelOrder(TreeNode root) {
        List<List<Integer>> result = new ArrayList<>();
        if (root == null) {
            return result;
        }

        LinkedListQueue<TreeNode> queue = new LinkedListQueue<>();
        queue.offer(root);
        boolean odd = true;
        int c1 = 1; // 当前层节点数
        while (!queue.isEmpty()) {
            LinkedList<Integer> sub = new LinkedList<>();   // 保存每一层
            int c2 = 0; // 下一层节点数
            for (int i = 0; i < c1; i++) {
                TreeNode poll = queue.poll();
                if (odd) {
                    sub.offerLast(poll.val);
                } else {
                    sub.offerFirst(poll.val);
                }
                if (poll.left != null) {
                    queue.offer(poll.left);
                    c2++;
                }
                if (poll.right != null) {
                    queue.offer(poll.right);
                    c2++;
                }
            }
            odd = !odd;
            result.add(sub);
            System.out.println();
            c1 = c2;
        }
        return result;
    }
    public static void main(String[] args) {
        TreeNode root = new TreeNode(
                new TreeNode(
                        new TreeNode(4),
                        2,
                        new TreeNode(5)
                ),
                1,
                new TreeNode(
                        new TreeNode(6),
                        3,
                        new TreeNode(7)
                )
        );
        List<List<Integer>> lists = zigzagLevelOrder(root);
        System.out.println(lists);
    }
}
